﻿using DAL;
using Models;
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Transactions;

namespace BLL
{
    public class B_Release_Result
    {
        public bool save_result(List<Models.t_data> ts, List<Models.g_data> gs)
        {
            BLL.B_G b_G = new BLL.B_G();
            BLL.B_T b_T = new BLL.B_T();
            BLL.B_Student b_Student = new BLL.B_Student();
            BLL.B_Group b_Group = new BLL.B_Group();
            BLL.B_Teacher b_Teacher = new BLL.B_Teacher();

            bool res;

            using (TransactionScope tx = new TransactionScope())//事务处理
            {
                var res_g = b_G.save_result(gs);
                var res_t = b_T.save_result(ts);

                var students = b_Student.GetList();
                var all_groups = b_Group.getList();
                var all_teachers = b_Teacher.GetList();

                foreach (g_data g_data in gs) 
                {
                    students.Where(stu => stu.group_id == g_data.g_id).ToList().ForEach(stu => stu.group_id = g_data.g_id);
                    all_groups.Where(group => group.group_id == g_data.g_id).ToList().ForEach(group => group.teacher_id = g_data.t_id);
                }

                foreach (Teacher t_data in all_teachers)
                {
                    all_groups.Where(group => group.teacher_id == t_data.teacher_id).ToList().ForEach(group => group.teacher_name = t_data.teacher_name);
                }

                var res_stu = b_Student.save_List(students);
                var res_groups = b_Group.save_List(all_groups);

                if (res_g && res_t && res_stu && res_groups)
                {
                    tx.Complete();
                    res = true;
                }
                else
                {
                    tx.Dispose();
                    res = false;
                }
            }
            return res;
        }
    }
}
